package com.epro.dx.activity.creditcard;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.ActionBar.LayoutParams;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.epro.dx.R;
import com.epro.dx.activity.BaseFragmentActivity;
import com.epro.dx.activity.PaymentCompleteActivity;
import com.epro.dx.listenner.GetCreditCardInfoListenner;
import com.epro.dx.pullview.PullToRefreshBase;
import com.epro.dx.pullview.PullToRefreshBase.Mode;
import com.epro.dx.pullview.PullToRefreshListView;
import com.epro.dx.task.BaseNeedReLoginTask;
import com.epro.dx.util.ActivityUtil;
import com.epro.dx.util.AsyncTaskUtil;
import com.epro.dx.util.GetCreditCardInfoAsyncTask;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.HitBuilders.ScreenViewBuilder;
import com.google.android.gms.analytics.ecommerce.Product;
import com.google.android.gms.analytics.ecommerce.ProductAction;
import com.weipu.common.constants.Constant;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.facade.exception.DxException;
import com.weipu.common.facade.factory.ProviderFactory;
import com.weipu.common.facade.model.CreditCardInfo;
import com.weipu.common.facade.model.CreditCardModel;
import com.weipu.common.facade.model.CreditCardPayRespose;
import com.weipu.common.facade.model.Lines;
import com.weipu.common.facade.model.SimpleCreditCard;
import com.weipu.common.util.AlertToast;
import com.weipu.common.util.SecurityUtil;
import com.weipu.common.util.StringUtil;

/*
 * 已保存的信用卡列表
 * */
public class CreditCardListActivity extends BaseFragmentActivity implements
		OnClickListener {

	private static final String TAG = "CreditCardListActivity";
	// topbar
	// private RelativeLayout backButton;
	private LinearLayout topRightButton;
	// private TextViewScoll pageTitle;
	// private ImageButton topRightButtonImg;

	// 信用卡列表
	private PullToRefreshListView creditCardList;

	// 提交支付按钮
	private Button pay;

	// 当前选中的条目
	private int choosePosition = -1;

	//输入框输入内容存储
	private HashMap<Integer,Object> inputText = new HashMap<Integer, Object>();
	
	private List<SimpleCreditCard> creditCards = new ArrayList<SimpleCreditCard>();

	private String cardFlow;
	private CreditCardListAdaptor creditCardListAdaptor;

	private AlertDialog securityCodeDialog;

	private Button btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn0,
			btn_del, btn_conf;

	private Editable editable;

	//订单号
	private String orderNumber=null;
	
	private int pageIndex = 1;
	private ArrayList<Lines> lines;
	private String couponCode = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_creditcardlist);
		Intent intent=getIntent();
		List<SimpleCreditCard> mCreditCards = null;
		if(null!=intent){
			mCreditCards = intent.getParcelableArrayListExtra("CreditCards");
			orderNumber = intent.getStringExtra(ServerConstant.Parameter.PARAMETER_NAME_ORDER_NUMBER);
			cardFlow=intent.getStringExtra("CardFlow");
			lines = intent.getParcelableArrayListExtra("Lines");
			couponCode  = intent.getStringExtra("CouponCode");
		}
		if (null == mCreditCards) {
			finish();
			return;
		}
		creditCards.addAll(mCreditCards);
		setTitleContent(R.string.creditcard_add_pagename).setFocusable(false);
		initView();
		initData();
		setEvent();
	}

	@Override
	protected void onResume() {
		super.onResume();
		sendScreen();
	}
	private void setEvent() {
		// 返回按钮
		// backButton.setOnClickListener(this);
		topbarLeftTv.setOnClickListener(this);

		// 信用卡新增按钮
		// topRightButton.setOnClickListener(this);

		// 提交支付按钮
		pay.setOnClickListener(this);
		
		//信用卡列表的下拉刷新与上拉加载
		creditCardList.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {

			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				// 下拉刷新
				pageIndex=1;
				getCerditCards(true);
			}

			@Override
			public void onPullUpToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				// 上拉加载
				++pageIndex;
				getCerditCards(false);
			}
		});
	}

	private void getCerditCards(final boolean isPullDown){
		AsyncTaskUtil.executeTask(new GetCreditCardInfoAsyncTask(new GetCreditCardInfoListenner() {
			
			@Override
			public void onPreGetInfo() {
				showLoadingLayout(null);
			}

			@Override
			public void onGetInfoComplect(CreditCardInfo creditCardInfo) {
				// TODO Auto-generated method stub
				List<SimpleCreditCard> cards = creditCardInfo.getsCreditCards();
				if(null!=cards){
					if(isPullDown){
						creditCards.clear();
					}
					creditCards.addAll(cards);
					if(cards.size()<Constant.LIST_PAGE_COUNT){
						creditCardList.setMode(Mode.PULL_FROM_START);
					}else{
						creditCardList.setMode(Mode.BOTH);
					}
					creditCardListAdaptor.notifyDataSetChanged();
				}
			}

			@Override
			public void onGetInfoFinish() {
				// TODO Auto-generated method stub
				hideAllLayout();
				creditCardList.onRefreshComplete();
			}
			
		}, CreditCardListActivity.this,pageIndex));
	}
	private void initData() {
		// // 设置页面显示内容
		// pageTitle.setText(R.string.creditcard_add_pagename);

		// 信用卡列表信息
		if(creditCards.size()<Constant.LIST_PAGE_COUNT){
			creditCardList.setMode(Mode.PULL_FROM_START);
		}else{
			creditCardList.setMode(Mode.BOTH);
		}
		creditCardListAdaptor = new CreditCardListAdaptor();
		creditCardList.setAdapter(creditCardListAdaptor);
	}

	private void initView() {
		// backButton = (RelativeLayout) findViewById(R.id.topbar_white_back);
		setLeftBtnContent(true, -1);
		topRightButton = (LinearLayout) findViewById(R.id.topbar_right_cart_layout);
		topRightButton
				.setBackgroundResource(R.drawable.add_credit_card_selector);
		topRightButton.setVisibility(View.VISIBLE);
		topRightButton.setOnClickListener(this);
		// pageTitle = (TextViewScoll) findViewById(R.id.topbar_white_title_tv);
		// topRightButtonImg = (ImageButton)
		// findViewById(R.id.topbar_white_right_img);
		// topRightButtonImg.setImageResource(R.drawable.add_credit_card);
		creditCardList = (PullToRefreshListView) findViewById(R.id.creditcard_list);

		pay = (Button) findViewById(R.id.creditcard_list_bt_pay);

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.topbar_left_tv:// 返回上一个页面
			showConfirmGiveUpPayDialog();
			break;
		case R.id.topbar_right_cart_layout:// 跳转到信用卡新增页面
			Intent i = new Intent(CreditCardListActivity.this,
					AddCreditCardActivity.class);
			i.putExtra("CardFlow", cardFlow);
			i.putExtra(ServerConstant.Parameter.PARAMETER_NAME_ORDER_NUMBER, orderNumber);
			startActivity(i);
			break;
		case R.id.creditcard_list_bt_pay:// 执行提交支付逻辑
			//校验是否选中一个信用卡并且已经输入安全码
			if(choosePosition!=-1){
				if(inputText.containsKey(choosePosition) && !TextUtils.isEmpty(inputText.get(choosePosition).toString())){
					//执行支付逻辑
					CreditCardModel model = new CreditCardModel();
					model.setCreditCardID(creditCards.get(choosePosition).getId());
					model.setCreditCardTokenID(creditCards.get(choosePosition).getId());
					String securityCodeStr=inputText.get(choosePosition).toString();
					try {
						securityCodeStr=SecurityUtil.aesEncrypt(securityCodeStr);
					} catch (Exception e) {
						//加密异常
						securityCodeStr=inputText.get(choosePosition).toString();
					}
					model.setCVVCode(securityCodeStr);
					model.setGatewayType(cardFlow);
					AsyncTaskUtil.executeTask(new PayTask(model));
				}else{
					// 提示安全码不能为空
					showToast( getString(R.string.creditcard_no_security_code));
				}
			}else{
				// 提示选择一个信用卡
				showToast(getString(R.string.creditcard_notchoose_creditcard));
			}
			break;

		default:
			break;
		}
	}
	
	/**
	 * @author tony
	 * 支付
	 */
	class PayTask extends BaseNeedReLoginTask{

		private CreditCardModel creditCardToken;
		private CreditCardPayRespose payRespose;
		public PayTask(CreditCardModel creditCardToken){
			this.creditCardToken = creditCardToken;
			
		}
		@Override
		protected void onPreExecute() {
			showLoadingLayout(null);
		}
		@Override
		protected String doInBackground(Void... arg0) {
			try {
				payRespose = ProviderFactory.createCreditCardServiceProvider().doCreditCardCheckout(ActivityUtil.getCustomerID()+"", ActivityUtil.getCustomerToken(), orderNumber, null, true, false, null, creditCardToken,StringUtil.getConfig(CreditCardListActivity.this, ServerConstant.Parameter.PARAMETER_NAME_USER_EMAIL));
			} catch (DxException e) {
				return e.getErrCode();
			}
			return "0";
		}
		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if(!isFinishing()){
				hideAllLayout();
				if("0".equals(result)){
					//支付完成，判断支付状态并跳转相应页面
					if(null!=payRespose){
						Intent goToPaymentFinish = new Intent(CreditCardListActivity.this,PaymentCompleteActivity.class);
						goToPaymentFinish.putExtra("orderNumber", orderNumber);
						goToPaymentFinish.putExtra("payMoney", payRespose.getCurrencyCodeSymbol()+""+payRespose.getOrderTotal());
						goToPaymentFinish.putExtra("payMethod", "CreditCard");
						goToPaymentFinish.putExtra("cardType", creditCards.get(choosePosition).getCardType());
						
						int responseResult = payRespose.getResponseResult();
						switch (responseResult) {
						case 0:
						case 3:
							//支付成功
							goToPaymentFinish.putExtra("payStatus", 0);
							//衡量交易
							mesureTransaction(orderNumber, payRespose.getOrderTotal());
							break;
						case 1:
							//支付失败
							goToPaymentFinish.putExtra("payStatus", 1);
							break;
						case 2:
							//待定
							goToPaymentFinish.putExtra("payStatus", 2);
							break;

						default:
							break;
						}
						startActivity(goToPaymentFinish);
					}
				}else if(!isRelogin){
					// 出现异常，土司提示
					AlertToast.alert(CreditCardListActivity.this,
							ServerConstant.ReturnCode.MESSAGEMAP.get(result));
				}
			}
		}
		@Override
		protected Context setContext() {
			return CreditCardListActivity.this;
		}
		@Override
		protected BaseNeedReLoginTask setTask() {
			return new PayTask(creditCardToken);
		}
	}
	
	// 信用卡列表数据适配器
	class CreditCardListAdaptor extends BaseAdapter {

		// 输入框输入内容存储
		private MyWatcher myWatcher = null;

		// private MyFocus myFocus;
		public CreditCardListAdaptor() {
			myWatcher = new MyWatcher();
		}

		@Override
		public int getCount() {
			return creditCards.size();
		}

		@Override
		public SimpleCreditCard getItem(int position) {
			return creditCards.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup group) {
			final HolderView holder;
			if (convertView == null) {
				holder = new HolderView();
				// myFocus = new MyFocus();
				convertView = View.inflate(CreditCardListActivity.this,
						R.layout.item_creditcard_list, null);
				holder.helpBt = (ImageView) convertView
						.findViewById(R.id.item_creditcard_security_code_help);
				holder.radioBt = (RadioButton) convertView
						.findViewById(R.id.item_creditcard_radiobt);
				holder.securityCode = (EditText) convertView
						.findViewById(R.id.item_creditcard_security_code);
				holder.cardHolder = (TextView) convertView
						.findViewById(R.id.creditcard_holder);
				holder.cardNumber = (TextView) convertView
						.findViewById(R.id.item_creditcard_cardnumber);
				holder.cardIcon = (ImageView) convertView
						.findViewById(R.id.item_creditcard_cardimg);
				convertView.setTag(holder);
			} else {
				holder = (HolderView) convertView.getTag();
			}
			SimpleCreditCard scc = creditCards.get(position);
			if (null != scc) {
				holder.cardHolder.setText(scc.getCardHolder());
				holder.cardNumber.setText(scc.getCardNum());
			}
			String cardType = scc.getCardType();
			Log.i("Ttt", cardType + " cardType");
			holder.cardIcon.setImageResource(ActivityUtil
					.getCardTypeResId(cardType));
			holder.securityCode.setTag(position);
			holder.radioBt
					.setChecked(choosePosition == position ? true : false);
			View currentFocus = CreditCardListActivity.this.getCurrentFocus();
			if (currentFocus != null) {
				currentFocus.clearFocus();
			}
			holder.securityCode.removeTextChangedListener(myWatcher);
			if (inputText.containsKey(position)) {
				holder.securityCode.setText(inputText.get(position).toString());
			} else {
				holder.securityCode.setText("");
			}
			holder.securityCode.addTextChangedListener(myWatcher);
			holder.helpBt.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					// 弹窗显示信用卡安全码指示页面
					Intent i = new Intent(CreditCardListActivity.this,
							SecurityCodeHelpActivity.class);
					startActivity(i);
					overridePendingTransition(R.anim.scale_in, R.anim.alpha_out);
				}
			});
			holder.securityCode.setOnClickListener(new OnClickListener() {

				AlertDialog dialog = null;

				@Override
				public void onClick(View v) {
					choosePosition = position;
					notifyDataSetChanged();
					View dialogView = View.inflate(CreditCardListActivity.this,
							R.layout.security_code_dialog/* dialog_input */,
							null);
					TextView title = (TextView) dialogView
							.findViewById(R.id.dialog_input_title);
					title.setText(R.string.creditcard_list_dialog_input_title);
					final EditText inputCode = (EditText) dialogView
							.findViewById(R.id.dialog_input_et);
					editable = inputCode.getEditableText();
					showSecurityCodeDialog(dialogView);
					intKeyboradView(dialogView);
					setDialogBtnListenner(inputCode);
					btn_conf.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							String code = inputCode.getText().toString().trim();
							if (!TextUtils.isEmpty(code)) {
								holder.securityCode.setText(code);
								
							}
							securityCodeDialog.dismiss();
							// button.requestFocus();
						}
					});
					// Button cancelBt = (Button)
					// dialogView.findViewById(R.id.dialog_input_Cancel);
					// Button confirmBt = (Button)
					// dialogView.findViewById(R.id.dialog_input_Confirm);
					// cancelBt.setText(R.string.creditcard_list_dialog_input_cancel);
					// confirmBt.setText(R.string.creditcard_list_dialog_input_confirm);
					// cancelBt.setOnClickListener(new OnClickListener() {
					//
					// @Override
					// public void onClick(View v) {
					// dialog.dismiss();
					// }
					// });
					// confirmBt.setOnClickListener(new OnClickListener() {
					//
					// @Override
					// public void onClick(View v) {
					// String code = inputCode.getText().toString().trim();
					// if(!TextUtils.isEmpty(code)){
					// holder.securityCode.setText(code);
					// }
					// dialog.dismiss();
					// }
					// });
					// Timer timer = new Timer();
					// timer.schedule(new TimerTask()
					// {
					//
					// public void run()
					// {
					// InputMethodManager inputManager =
					// (InputMethodManager)inputCode.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
					// inputManager.showSoftInput(inputCode, 0);
					// }
					//
					// },
					// 500);
				}
			});
			convertView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// 点击整个条目选中单选按钮，文本编辑框获取焦点
					choosePosition = position;
					notifyDataSetChanged();
				}
			});
			convertView.setOnLongClickListener(new OnLongClickListener() {

				@Override
				public boolean onLongClick(View v) {
					// 删除选中位置的信用卡
					AlertDialog dialog;
					AlertDialog.Builder builder = new AlertDialog.Builder(
							CreditCardListActivity.this);
					builder.setTitle(R.string.delete);
					builder.setMessage(R.string.creditcard_list_dialog_delete_message);
					builder.setNegativeButton(R.string.creditcard_list_dialog_delete_no, new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
					builder.setPositiveButton(R.string.creditcard_list_dialog_delete_yes, new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							//执行删除信用卡逻辑
							AsyncTaskUtil.executeTask(new DeleteCreditCardTask(getItem(position).getId(),position));
							dialog.dismiss();
						}
					});
					dialog = builder.create();
					dialog.show();
					return false;
				}
			});
			return convertView;
		}

		class HolderView {
			// 安全码
			EditText securityCode;
			// 帮助按钮
			ImageView helpBt;
			// 单选按钮
			RadioButton radioBt;

			TextView cardNumber;

			TextView cardHolder;

			ImageView cardIcon;
		}

		// 自定义文本框监控
		class MyWatcher implements TextWatcher {
			@Override
			public void afterTextChanged(Editable s) {
				inputText.put(choosePosition, s.toString());
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {

			}
		}
	}

	/**
	 * @author Tony 删除信用卡
	 */
	class DeleteCreditCardTask extends BaseNeedReLoginTask {

		private String creditCardID;
		private int position;

		public DeleteCreditCardTask(String creditCardID, int position) {
			this.creditCardID = creditCardID;
			this.position = position;
		}

		@Override
		protected void onPreExecute() {
			showLoadingLayout(null);
		}

		@Override
		protected String doInBackground(Void... params) {
			try {
				ProviderFactory.createCreditCardServiceProvider()
						.deleteCreditCard(creditCardID, Integer.parseInt(ActivityUtil.getCustomerID()+""),ActivityUtil.getCustomerToken());
			} catch (DxException e) {
				return e.getErrCode();
			}
			return "0";
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (!isFinishing()) {
				hideAllLayout();
				if ("0".equals(result)) {
					// 删除成功，更新UI
					creditCards.remove(position);
					creditCardListAdaptor.notifyDataSetChanged();
				} else if(!isRelogin){
					// 出现异常，土司提示
					AlertToast.alert(CreditCardListActivity.this,
							ServerConstant.ReturnCode.MESSAGEMAP.get(result));
				}
			}

		}

		@Override
		protected Context setContext() {
			return CreditCardListActivity.this;
		}

		@Override
		protected BaseNeedReLoginTask setTask() {
			return new DeleteCreditCardTask(creditCardID, position);
		}

	}

	private void showSecurityCodeDialog(final View dialogView) {

		securityCodeDialog = new AlertDialog.Builder(this).create();
		// dialog.setView(dialogView);
		securityCodeDialog.show();
		// 关键在下面的两行,使用window.setContentView,替换整个对话框窗口的布局
		Window window = securityCodeDialog.getWindow();
		window.setGravity(Gravity.BOTTOM);
		window.setContentView(dialogView);
		window.setWindowAnimations(R.style.KeybroadAnimation);
		window.setLayout(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		// window.clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
		// WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
		window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
	}

	private void intKeyboradView(final View keyboardView) {

		btn0 = (Button) keyboardView.findViewById(R.id.keyboard_btn0);
		btn1 = (Button) keyboardView.findViewById(R.id.keyboard_btn1);
		btn2 = (Button) keyboardView.findViewById(R.id.keyboard_btn2);
		btn3 = (Button) keyboardView.findViewById(R.id.keyboard_btn3);
		btn4 = (Button) keyboardView.findViewById(R.id.keyboard_btn4);
		btn5 = (Button) keyboardView.findViewById(R.id.keyboard_btn5);
		btn6 = (Button) keyboardView.findViewById(R.id.keyboard_btn6);
		btn7 = (Button) keyboardView.findViewById(R.id.keyboard_btn7);
		btn8 = (Button) keyboardView.findViewById(R.id.keyboard_btn8);
		btn9 = (Button) keyboardView.findViewById(R.id.keyboard_btn9);
		btn_del = (Button) keyboardView.findViewById(R.id.keyboard_btn_del);
		btn_conf = (Button) keyboardView.findViewById(R.id.keyboard_btn_conf);
		updateKeyBoard();
	}

	/**
	 * 键盘Button事件
	 * 
	 * @param editText
	 */
	private void setDialogBtnListenner(final EditText editText) {
		btn0.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				int index = editText.getSelectionStart();
				String str = btn0.getText().toString();
				editable.insert(index, str);
			}
		});
		btn1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				int index = editText.getSelectionStart();
				String str = btn1.getText().toString();
				editable.insert(index, str);
			}
		});
		btn2.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				int index = editText.getSelectionStart();
				String str = btn2.getText().toString();
				editable.insert(index, str);
			}
		});
		btn3.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				int index = editText.getSelectionStart();
				String str = btn3.getText().toString();
				editable.insert(index, str);
			}
		});
		btn4.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				int index = editText.getSelectionStart();
				String str = btn4.getText().toString();
				editable.insert(index, str);
			}
		});
		btn5.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				int index = editText.getSelectionStart();
				String str = btn5.getText().toString();
				editable.insert(index, str);
			}
		});
		btn6.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				int index = editText.getSelectionStart();
				String str = btn6.getText().toString();
				editable.insert(index, str);
			}
		});
		btn7.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				int index = editText.getSelectionStart();
				String str = btn7.getText().toString();
				editable.insert(index, str);
			}
		});
		btn8.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				int index = editText.getSelectionStart();
				String str = btn8.getText().toString();
				editable.insert(index, str);
			}
		});
		btn9.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				int index = editText.getSelectionStart();
				String str = btn9.getText().toString();
				editable.insert(index, str);
			}
		});

		btn_del.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				try {
					int index = editText.getSelectionStart();
					editable.delete(index - 1, index);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});

		btn_del.setOnLongClickListener(new OnLongClickListener() {

			@Override
			public boolean onLongClick(View arg0) {
				editText.setText("");
				return false;
			}
		});

	}

	private void updateKeyBoard() {
		int[] randomNum = ActivityUtil.getRandomNum();
		btn0.setText(randomNum[0] + "");
		btn1.setText(randomNum[1] + "");
		btn2.setText(randomNum[2] + "");
		btn3.setText(randomNum[3] + "");
		btn4.setText(randomNum[4] + "");
		btn5.setText(randomNum[5] + "");
		btn6.setText(randomNum[6] + "");
		btn7.setText(randomNum[7] + "");
		btn8.setText(randomNum[8] + "");
		btn9.setText(randomNum[9] + "");
	}

	/**
	 *  GA衡量交易
	 */
	private void mesureTransaction(String orderNumber,double money){
		ScreenViewBuilder builder = new HitBuilders.ScreenViewBuilder();
		if(null!=lines && lines.size()!=0){
			for(int i = 0;i<lines.size();i++){
				Lines line = lines.get(i);
				Product product = new Product()
				.setId(String.valueOf(line.getSku()))
				.setName(line.getName())
				.setQuantity(line.getQty())
				.setPrice(line.getSellingPrice());
				builder.addProduct(product);
			}
		}
		if (null != orderNumber) {
			ProductAction productAction = new ProductAction(
					ProductAction.ACTION_PURCHASE)
					.setTransactionId(orderNumber)
					// 此次交易关联的实体（例如某家商店）。
					.setTransactionAffiliation("DX Android Phone - Online")
					// 交易的总收入，含税费和运费。
					.setTransactionRevenue(money)
					// 交易的总税费。
					.setTransactionTax(0)
					// 交易的总运费。
					.setTransactionShipping(0)
					// 订单使用的Coupon
					.setTransactionCouponCode(couponCode);
			builder.setProductAction(productAction);
			
			theTracker.send(builder.build());
		}
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK){
			showConfirmGiveUpPayDialog();
		}
		return super.onKeyDown(keyCode, event);
	}
}
